import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.core.config import settings
from app.api.routes import api_router
from utils.logger import setup_logger
from database import init_db

# 设置日志
logger = setup_logger('main', 'logs/main.log')

# 创建FastAPI应用实例
app = FastAPI(
    title=settings.APP_NAME,
    description=settings.APP_DESCRIPTION,
    version=settings.APP_VERSION,
    docs_url="/docs" if settings.DEBUG else None,
    redoc_url="/redoc" if settings.DEBUG else None
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.CORS_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 在应用启动时初始化数据库
@app.on_event("startup")
async def startup_event():
    init_db()
    logger.info(f"{settings.APP_NAME} 服务启动")

# 注册API路由
app.include_router(api_router, prefix=settings.API_V1_STR)

@app.get("/")
async def root():
    """应用程序根路径"""
    return {
        "app_name": settings.APP_NAME,
        "version": settings.APP_VERSION,
        "docs_url": "/docs",
        "api_url": settings.API_V1_STR
    }

@app.get("/health")
async def health_check():
    """健康检查接口"""
    return {"status": "healthy"}

@app.on_event("shutdown")
async def shutdown_event():
    logger.info(f"{settings.APP_NAME} 服务关闭")

if __name__ == "__main__":
    logger.info(f"启动 {settings.APP_NAME} 服务")
    uvicorn.run("main:app", host="0.0.0.0", port=5002, reload=settings.DEBUG) 

